package org.sundatagroup.aurora.show.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.sundatagroup.aurora.core.entity.pojo.Project;
import org.sundatagroup.aurora.core.service.ProjectService;
import org.sundatagroup.aurora.show.service.SidDispatcher;

/**
 * <p>直接打开, 用于显示项目展示的网页. 该 Controller 里面的接口均为打开网页, 而非传输数据.
 * </p>
 * 
 * @version 0.2.0
 * <br>确定了该类的功能, 移除了非打开新网页的请求
 * 
 * @author Zdream
 * @date 2018-05-25
 * @since 0.1
 */
@RequestMapping("/aurora")
@Controller
public class DisplayController {
	
	@Autowired
	private ProjectService projectService;

	@Autowired
	private SidDispatcher sidDispatcher;
	
	/**
	 * <p>使用工程的 ID 来打开页面
	 * <p>在版本 0.2.0 之后, 不再向没有指定屏幕号 <code>sid</code> 的屏幕创建屏幕号了,
	 * 而且后端, 包括监控端也不再对其进行状态跟踪了.
	 * </p>
	 * @version 0.2.0
	 *   不再对没有屏幕号的屏幕创建屏幕号了
	 * @param pid
	 *   工程编号
	 * @return
	 */
	@RequestMapping(path = { "project/{pid}" })
    public ModelAndView displayProject(@PathVariable int pid,
							   @RequestParam(required = false) String sid,
							   HttpSession session) {
		ModelAndView mv = new ModelAndView("show/display");
		mv.addObject("displayType", "project");

		Project p = projectService.queryByPid(pid);
		if (p == null)
			return null;

		mv.addObject("pid", pid);
		mv.addObject("sid", sid); // 现在 sid 可能为 null
		return mv;
    }

	/**
	 * 返回所有project的列表,点击可直接访问项目.项目过多时分页,默认一页10个
	 */
	@RequestMapping("project/index")
	public ModelAndView projectIndex(@RequestParam(required = false)Integer start,
								@RequestParam(required = false) Integer size){
		size = (size == null) ? 10 : size;
		start = (start == null) ? 0 : start;
		ModelAndView mv = new ModelAndView("project");
		List<Integer> projectHref = new ArrayList<>();// 存储翻页的链接,在project.html中用js构造

		List<Project> project = projectService.queryByPage(start, size);
		mv.addObject("project", project);
		int projectNum = projectService.countProjects();
		int pageCounter = projectNum / size;
		if ((projectNum - size) % size > 0)
			pageCounter++;
		if (projectNum <= size)
			pageCounter--; // 只有1页不显示页码

		for (int i = 0; i < pageCounter; i++) {
			projectHref.add(i + 1);
		}
		String sid = sidDispatcher.createSid();

		mv.addObject("projectHref", projectHref);
		mv.addObject("pageCounter", pageCounter);
		mv.addObject("sid", sid);
		mv.addObject("size", size);

		return mv;
	}

	/**
	 * 等待页
	 */
	@RequestMapping("show/waiting")
	public ModelAndView waiting(){
		ModelAndView mv = new ModelAndView("show/waiting");
		return mv;
	}
}
